<template>
    <div class="operatePointRules">
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/pointRules' }">节点规则设置</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='add'">新增</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='edit'">编辑</el-breadcrumb-item>
        </el-breadcrumb>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="180px" class="demo-ruleForm">
            <el-form-item label="角色：">
                <el-select v-model="ruleForm.payForRole" :disabled="brokerageCount>0&&pageType=='edit'">
                    <el-option label="职业经纪人" :value="0"></el-option>
                    <el-option label="网络推客" :value="1"></el-option>
                    <el-option label="自来客" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="节点规则名称：" prop='nodeRuleName'>
                <el-input v-model="ruleForm.nodeRuleName" class="w-800" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item label="经纪人奖励：" v-if="ruleForm.payForRole==0">
                <el-radio v-model="ruleForm.isAward" :label="1" :disabled="brokerageCount>0&&pageType=='edit'">有</el-radio>
                <el-radio v-model="ruleForm.isAward" :label="0" :disabled="brokerageCount>0&&pageType=='edit'">无</el-radio>
            </el-form-item>

            <h5>设置经纪人跟进规则</h5>

            <!--开发商节点设置-->
            <el-form-item label="开发商节点设置：" required>
                {{developComputed}}
                <el-button type="primary" size="mini" @click="showDevelopDialog" :disabled="brokerageCount>0&&pageType=='edit'">{{developComputed.length==0 ? '新增':'编辑'}}</el-button>
            </el-form-item>

            <!--经纪人及网络推客跟进节点设置-->
            <div v-if="ruleForm.payForRole==0 || ruleForm.payForRole==1">
                <el-form-item :label="ruleForm.payForRole==0?'经纪人跟进节点设置：':'网络推客跟进节点设置：'" required></el-form-item>
                <el-form-item v-for="(item,index) in ruleForm.broker" :key="index" :label="'节点'+(index+1)+':'" required>
                    {{item | showPoint}}
                    <el-button type="primary" size="mini" @click="showBrokerDialog(index)" :disabled="brokerageCount>0&&pageType=='edit'">{{item.length ==0? '新增':'编辑'}}</el-button>
                    <el-button type="danger" size="mini" @click="deleteBrokerHandle(item)" :disabled="brokerageCount>0&&pageType=='edit'" v-show="ruleForm.broker.length>1">删除</el-button>
                </el-form-item>
                <el-form-item label="">
                    <el-button style="width: 200px; height: 20px; line-height: 4px;" size="mini" v-show="ruleForm.broker.length<5" :disabled="brokerageCount>0&&pageType=='edit'" @click="addBrokerHandle">新增</el-button>
                </el-form-item>
            </div>

            <!--设置经纪人奖励节点-->
            <div v-if="ruleForm.payForRole==0 && ruleForm.isAward==1">
                <h5>设置经纪人奖励节点</h5>
                <el-form-item label="节点设置：" required></el-form-item>
                <el-form-item v-for="(item,index) in ruleForm.awardsNodes" :key="index" :label="'节点'+(index+1)+':'" required>
                    {{item | showPoint}}
                    <el-button type="primary" size="mini" :disabled="brokerageCount>0&&pageType=='edit'" @click="showAwardDialog(index)">{{item.length ==0? '新增':'编辑'}}</el-button>
                    <el-button type="danger" size="mini" :disabled="brokerageCount>0&&pageType=='edit'" @click="deleteAwardHandle(item)" v-show="ruleForm.awardsNodes.length>1">删除</el-button>
                </el-form-item>
                <el-form-item label="">
                    <el-button style="width: 200px; height: 20px; line-height: 4px;" size="mini" v-show="ruleForm.awardsNodes.length<2" :disabled="brokerageCount>0&&pageType=='edit'" @click="addAwardHandle">新增</el-button>
                </el-form-item>
            </div>

            <!--保存-->
            <el-form-item>
                <el-button type="success" @click="submitForm('ruleForm')">保存</el-button>
                <el-button @click="cancelHandle()">取消</el-button>
            </el-form-item>
        </el-form>

        <!--开发商节点设置弹窗-->
        <el-dialog title="编辑开发商节点" :visible.sync="dialogVisible1" width="600px" :before-close="confirmDevelop">
            <div class="sort-box">
                <el-transfer
                    filterable
                    :filter-method="filterMethod"
                    v-model="devTemp"
                    :data="pointList"
                    target-order="push"
                    @right-check-change="checkChange"
                >
                </el-transfer>
                <div class="up" @click="upHandle(devTemp)"><div class="my-arrow"></div></div>
                <div class="down" @click="downHandle(devTemp)"><div class="my-arrow"></div></div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible1=false">取 消</el-button>
                <el-button type="primary" @click="confirmDevelop">确 定</el-button>
            </span>
        </el-dialog>
        <!--经纪人及网络推客跟进节点设置弹窗-->
        <el-dialog :title="ruleForm.payForRole==0?'编辑经纪人跟进节点':'编辑网络推客跟进节点'" :visible.sync="dialogVisible2" width="600px">
            <div class="sort-box">
                <el-transfer
                    filterable
                    :filter-method="filterMethod"
                    v-model="brokerChecked"
                    :data="pointList2"
                    target-order="push"
                    @right-check-change="checkChange"
                >
                </el-transfer>
                <div class="up" @click="upHandle(brokerChecked)"><div class="my-arrow"></div></div>
                <div class="down" @click="downHandle(brokerChecked)"><div class="my-arrow"></div></div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2=false">取 消</el-button>
                <el-button type="primary" @click="confirmBroker">确 定</el-button>
            </span>
        </el-dialog>
        <!--经纪人奖励节点设置弹窗-->
        <el-dialog title="编辑经纪人奖励节点" :visible.sync="dialogVisible3" width="600px">
            <div class="sort-box">
                <el-transfer
                    filterable
                    :filter-method="filterMethod"
                    v-model="awardChecked"
                    :data="pointList"
                    target-order="push"
                    @right-check-change="checkChange"
                >
                </el-transfer>
                <div class="up" @click="upHandle(awardChecked)"><div class="my-arrow"></div></div>
                <div class="down" @click="downHandle(awardChecked)"><div class="my-arrow"></div></div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible3=false">取 消</el-button>
                <el-button type="primary" @click="confirmAward">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import api from "@/api/apiPath"
let globalFollowList = []

export default {
    name:"operatePointRules",
    created() {
        globalFollowList = []
        this.pageType = this.$route.query.type
        this.axios.post(api.pointRulesNodeList,{}).then(res => {
            const temp = res.data.data
            temp.forEach(item => {
                if (item.nodeName == '回款') {
                    this.specialNode = {key: item.id, label: item.nodeName}
                    return // 回款节点不出现在开发商节点中
                }
                if (item.nodeName == '认购'){
                    this.rengou = {key: item.id, label: item.nodeName}
                }
                if (item.nodeName == '草签'){
                    this.caoqian = {key: item.id, label: item.nodeName}
                }
                if (item.nodeName == '签约'){
                    this.qianyue = {key: item.id, label: item.nodeName}
                }
                this.pointList.push({key: item.id, label: item.nodeName, isDivisible:item.isDivisible})
                globalFollowList.push({key: item.id, label: item.nodeName, isDivisible:item.isDivisible})
            })
            globalFollowList.push(this.specialNode)
            this.pointList2 = JSON.parse(JSON.stringify(globalFollowList))
            if(this.pageType == 'edit') {
                this.id = this.$route.query.id
                this.brokerageCount = this.$route.query.brokerageCount
                this.axios.post(api.findNodeRuleById,{id:this.id}).then(res => {
                    const temp = res.data.data
                    this.updateId = temp.id
                    this.createTime = temp.createTime
                    this.ruleForm.payForRole = temp.payForRole
                    this.ruleForm.nodeRuleName = temp.nodeRuleName
                    this.ruleForm.isAward = Number(temp.isAward)
                    this.ruleForm.develop = this.getSimpleArray(temp.developerNodes)
                    this.ruleForm.broker = temp.brokerageNodes
                    this.ruleForm.awardsNodes = temp.awardsNodes?temp.awardsNodes:[]
                })
            }
        })
    },
    mounted() {},
    components: {},
    data() {
        return {
            brokerageCount: '',
            pageType: '',
            pointList: [],//{key:1, label: '认购'},{key:2, label: '草签'},{key:3, label: '签约'},{key:4, label: '银行批贷'},{key:5, label: '交齐房款30%'}
            pointList2: [], // 这个list带回款，开发商的不带回款。
            pointList3: [], // 只有认购，签约
            specialNode: {},// 回款
            rengou: {}, // 认购
            caoqian: {}, // 草签
            qianyue: {}, // 签约
            ruleForm: {
                payForRole: 0, // 角色
                nodeRuleName: '', // 节点规则名称
                isAward: 1, // 经纪人奖励
                develop: [], // 开发商
                broker: [], // 经纪人
                awardsNodes: [], // 经纪人奖励
            },
            rules: {
                nodeRuleName: [
                    { required: true, message: '节点规则名称', trigger: 'blur' },
                ],
            },
            devTemp: [], // 开发商选定节点临时
            brokerChecked: [], // 经纪人选定节点临时
            awardChecked: [], // 经纪人奖励选定节点临时
            filterMethod(query, item) {
                return item.label.indexOf(query) > -1;
            },
            dialogVisible1: false,// 开发商节点弹窗
            dialogVisible2: false,// 经纪人节点弹窗
            dialogVisible3: false,// 经纪人奖励节点弹窗
        }
    },
    methods: {
        // 获取一维数组
        getSimpleArray(arr){
            let result = []
            arr.forEach(item => {
                result.push(item[0])
            })
            return result
        },
        // 跟进节点checked
        checkChange (val) {
            console.log(val);
            
            this.followChecked = val
        },
        // 跟进节点上移
        upHandle (followTemp) {
            if (this.followChecked && this.followChecked.length == 1) {
                const index = followTemp.indexOf(this.followChecked[0])
                if (index > 0) {
                    followTemp.splice(index, 1)
                    followTemp.splice(index-1, 0, this.followChecked[0])
                }
            }
        },
        // 跟进节点下移
        downHandle (followTemp) {
            if (this.followChecked && this.followChecked.length == 1) {
                const index = followTemp.indexOf(this.followChecked[0])
                if (index < followTemp.length-1) {
                    followTemp.splice(index, 1)
                    followTemp.splice(index+1, 0, this.followChecked[0])
                }
            }
        },
        /** -------------------------开发商节点的功能--------------------------- **/
        // 开发商节点设置
        showDevelopDialog () {
            this.dialogVisible1 = true
            this.devTemp = JSON.parse(JSON.stringify(this.ruleForm.develop))
        },
        // 开发商节点确定
        confirmDevelop () {
            this.ruleForm.develop = this.devTemp
            this.dialogVisible1 = false
        },
        /** -------------------------开发商节点的功能---------- end ----------------- **/
        /** -------------------------经纪人跟进节点的功能--------------------------- **/
        // 增加节点
        addBrokerHandle () {
            this.ruleForm.broker.push([])
        },
        deleteBrokerHandle (val) {
            const index = this.ruleForm.broker.indexOf(val)
            this.ruleForm.broker.splice(index,1)
        },
        // 展示弹框
        showBrokerDialog (index) {
            this.dialogVisible2 = true
            this.brokerIndex = index
            this.brokerChecked = this.ruleForm.broker[index]
        },
        confirmBroker () {
            // 判断所选内容是否有多个可拆分节点
            let index = 0
            this.brokerChecked.forEach(val=>{
                this.pointList2.find(item=>{
                    if(item.key == val && item.isDivisible == 1){
                        index = index+1
                    }
                })
            })
            if(index>1){
                this.$message({
                    type:'warning',
                    message:'多个可拆分节点不可为组合节点'
                })
                return
            }
            let flag = true
            if (this.brokerChecked.length > 0) {
                this.ruleForm.broker.forEach((arr,index) => {
                    if (index == this.brokerIndex) {
                        return
                    }
                    if (arr.length > 0) {
                        arr.forEach(item => {
                            if (this.brokerChecked.indexOf(item) != -1) {
                                this.$message.error('节点重复，请重新选择')
                                flag = false
                                return
                            }
                        })
                    }
                })
            }
            if (this.brokerChecked.length>1) {
                this.brokerChecked.forEach(item => {
                    if (item == this.specialNode.key) {
                        this.$message.error('回款不可为组合节点')
                        flag = false
                        return
                    }
                })
            }
            if (flag) {
                this.ruleForm.broker[this.brokerIndex] = this.brokerChecked
                this.dialogVisible2 = false
            }
        },
        /** -------------------------经纪人跟进节点的功能------------ end --------------- **/
        /** -------------------------经纪人奖励节点的功能--------------------------- **/
        // 增加节点
        addAwardHandle () {
            this.ruleForm.awardsNodes.push([])
        },
        deleteAwardHandle (val) {
            const index = this.ruleForm.awardsNodes.indexOf(val)
            this.ruleForm.awardsNodes.splice(index,1)
        },
        // 展示弹框
        showAwardDialog (index) {
            this.dialogVisible3 = true
            this.awardIndex = index
            this.awardChecked = this.ruleForm.awardsNodes[index]
        },
        confirmAward () {
            // 经纪人奖励不可为可拆分节点
            let index = 0
            this.awardChecked.forEach(val=>{
                this.pointList.find(item=>{
                    if(item.key == val && item.isDivisible == 1){
                        index = index+1
                    }
                })
            })
            if(index>0){
                this.$message({
                    type:'warning',
                    message:'经纪人奖励不可为可拆分节点'
                })
                return
            }
            let flag = true
            if (this.awardChecked.length>1) { // 奖励节点只能是单节点
                this.$message.info('奖励节点只能设置单节点')
                return
            }
            if (this.awardChecked.length == 1) {
                this.ruleForm.awardsNodes.forEach((arr,index) => {
                    if (index == this.awardIndex) {// 自身和自身不用判重
                        return
                    }
                    if (this.awardChecked.indexOf(arr[0]) != -1) {
                        this.$message.error('节点重复，请重新选择')
                        flag = false
                        return
                    }
                })
            }

            if (flag) {
                this.ruleForm.awardsNodes[this.awardIndex] = this.awardChecked
                this.dialogVisible3 = false
            }
        },
        /** -------------------------经纪人奖励节点的功能------------ end --------------- **/
        // 保存
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.develop.length == 0){
                        this.$message.error('请选择开发商节点')
                        return
                    }
                    if(this.pageType=='edit' && this.brokerageCount>0){// 历史数据编辑不做校验

                    } else {
                        if(this.ruleForm.payForRole==0 || this.ruleForm.payForRole==1){
                            // 经纪人节点不能为空
                            if (this.ruleForm.broker.length == 0){
                                this.$message.error('请选择经纪人跟进节点')
                                return
                            }
                            // 经纪人节点的每一项节点不能为空
                            if (this.ruleForm.broker.length>0) {
                                const temp = this.ruleForm.broker
                                for(let i=0; i<temp.length; i++){
                                    if(temp[i].length == 0) {
                                        this.$message.error('请选择经纪人跟进节点')
                                        return
                                    }
                                }
                            }
                            // 经纪人奖励节点不能为空
                            if (this.ruleForm.payForRole==0 && this.ruleForm.isAward==1) {

                                if (this.ruleForm.awardsNodes.length == 0){
                                    this.$message.error('请选择经纪人奖励节点')
                                    return
                                }
                                // 经纪人节点的每一项节点不能为空
                                if (this.ruleForm.awardsNodes.length>0) {
                                    const temp = this.ruleForm.awardsNodes
                                    for(let i=0; i<temp.length; i++){
                                        if(temp[i].length == 0) {
                                            this.$message.error('请选择经纪人奖励节点')
                                            return
                                        }
                                    }
                                }
                            }
                            // 先把经纪人跟进节点的二维数组变为一维数组
                            let brokerPointOneDimensional = []
                            this.ruleForm.broker.forEach(arrT => {
                                arrT.forEach(point => {
                                    brokerPointOneDimensional.push(point)
                                })
                            })
                            // 经纪人 认购必选，草签 签约必须二选一
                            if (brokerPointOneDimensional.indexOf(this.rengou.key) == -1) {
                                this.$message.error('认购必选，草签 签约必选一个')
                                return
                            }
                            if (brokerPointOneDimensional.indexOf(this.caoqian.key) == -1 && brokerPointOneDimensional.indexOf(this.qianyue.key) == -1) {
                                this.$message.error('认购必选，草签 签约必选一个')
                                return
                            }
                            if (brokerPointOneDimensional.indexOf(this.rengou.key) != 0) {
                                this.$message.error('认购必须是第一个节点')
                                return
                            }
                            // 判断经纪人跟进节点是否全部包含开发商节点
                            for(let i=0; i<this.ruleForm.develop.length; i++){
                                if(brokerPointOneDimensional.indexOf(this.ruleForm.develop[i])==-1){
                                    this.$message.error('开发商节点不在跟进节点中')
                                    return
                                }
                            }

                            if(this.ruleForm.awardsNodes && this.ruleForm.awardsNodes.length>0){
                                // 把经纪人奖励节点的二维数组变为一维数组
                                let brokerAwardsOneDemensional = []
                                this.ruleForm.awardsNodes.forEach(arrT => {
                                    arrT.forEach(point => {
                                        brokerAwardsOneDemensional.push(point)
                                    })
                                })

                                // 判断经纪人跟进节点是否全部包含经纪人奖励节点
                                for(let j=0; j<brokerAwardsOneDemensional.length; j++){
                                    if(brokerPointOneDimensional.indexOf(brokerAwardsOneDemensional[j])==-1){
                                        this.$message.error('经纪人奖励节点不在跟进节点中')
                                        return
                                    }
                                }
                            }

                        }
                    }

                    let param = {}
                    param.nodeRuleName = this.ruleForm.nodeRuleName
                    param.payForRole = this.ruleForm.payForRole
                    // 开发商节点得拆成二维数组
                    let developerNodesTemp = []
                    this.ruleForm.develop.forEach(item => {
                        developerNodesTemp.push([item])
                    })
                    param.developerNodes = developerNodesTemp
                    if (this.ruleForm.payForRole == 0 || this.ruleForm.payForRole==1){// 经纪人网络推客跟进节点
                        param.brokerageNodes = this.ruleForm.broker
                    }
                    if (this.ruleForm.payForRole == 0) {// 是否有经纪人奖励
                        param.isAward = this.ruleForm.isAward
                    }

                    if (this.ruleForm.payForRole == 0 && this.ruleForm.isAward == 1) {// 经纪人奖励节点
                        param.awardsNodes = this.ruleForm.awardsNodes
                    }
                    if (this.ruleForm.payForRole == 2) { // 自来客跟进节点同开发商节点
                        param.brokerageNodes = [this.ruleForm.develop]
                    }
                    param.operatorName = localStorage.cmsUser?JSON.parse(localStorage.cmsUser).name : ''
                    if (this.pageType == 'add') {
                        this.axios.post(api.pointRulesAddOne, param).then(res => {
                            if(res.data.code==200){
                                this.$message.success('保存成功')
                                this.$router.push({path: '/pointRules'})
                            }
                        })
                    } else {
                        param.id = this.updateId
                        param.createTime = this.createTime
                        this.axios.post(api.pointRulesUpdateOne, param).then(res => {
                            if(res.data.code==200){
                                this.$message.success('修改成功')
                                this.$router.push({path: '/pointRules'})
                            }
                        })
                    }

                } else {
                    return false;
                }
            });
        },
        cancelHandle(){
            this.$router.push({path: '/pointRules'})
        }
    },
    computed: {
        // 展示开发商节点
        developComputed () {
            let result = ''
            if (this.ruleForm.develop.length > 0) {
                this.ruleForm.develop.forEach(item => {
                    const followItem = this.pointList.find(follow => {
                        return follow.key == item
                    })
                    result += followItem.label + ', '
                })
            }
            result = result.substring(0,result.length-2)
            return result
        },
    },
    filters:{
        showPoint (val) {
            let result = ''
            if (val&& val.length > 0) {
                val.forEach(item => {
                    const followItem = globalFollowList.find(follow => {
                        return follow.key == item
                    })
                    result += followItem.label + ', '
                })
            }
            result = result.substring(0,result.length-2)
            return result
        }
    }
}
</script>
<style lang="stylus">
    .operatePointRules {
        .el-transfer .el-checkbox{
            display: block;
        }
        .sort-box{position: relative}
        .sort-box .up, .sort-box .down{
            position: absolute;
            width: 40px;
            height: 40px;
            border: 1px solid #ccc;
            line-height: 40px;
            text-align: center;
            border-radius: 50%;
            cursor: pointer;
            right: 0;
        }
        .sort-box .up:hover, .sort-box .down:hover{
            border: 1px solid #0d8ddb;
        }
        .sort-box .up{
            top: 35%;
        }
        .sort-box .down{
            top: 55%;
        }
        .sort-box .up .my-arrow, .sort-box .down .my-arrow{
            position: absolute;
            left: 10px;
            top: 10px;
            width: 20px;
            height: 20px;
            border-left: 1px solid #ccc;
            border-top: 1px solid #ccc;
        }
        .sort-box .up .my-arrow{
            top: 15px;
            transform: rotate(45deg);
        }
        .sort-box .down .my-arrow{
            top: 5px;
            transform: rotate(-135deg);
        }
    }
</style>
